<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>碰撞检测</title>
    <style>
        #div1 {
            width: 100px;
            height: 100px;
            background: green;
            position: absolute;
        }

        #div2 {
            width: 100px;
            height: 100px;
            background: yellow;
            position: absolute;
            left: 300px;
            top: 200px;
            z-index: -1;
        }
    </style>


</head>

<body>
    <div id="div1"></div>
    <div id="div2"></div>
</body>

</html>
<script>
    window.onload = function () {
        var oDiv = document.getElementById('div1');
        var oDiv2 = document.getElementById('div2');
        var disX = 0;
        var disY = 0;
        oDiv.onmousedown = function (ev) {
            var ev = ev || window.event;
            disX = ev.clientX - oDiv.offsetLeft;
            disY = ev.clientY - oDiv.offsetTop;
            document.onmousemove = function (ev) {
                var ev = ev || window.event;
                var t1 = oDiv.offsetTop;
                var l1 = oDiv.offsetLeft;
                var r1 = oDiv.offsetLeft + oDiv.offsetWidth;
                var b1 = oDiv.offsetTop + oDiv.offsetHeight;
                var t2 = oDiv2.offsetTop;
                var l2 = oDiv2.offsetLeft;
                var r2 = oDiv2.offsetLeft + oDiv2.offsetWidth;
                var b2 = oDiv2.offsetTop + oDiv2.offsetHeight;
                if (b1 < t2 || l1 > r2 || t1 > b2 || r1 < l2) {// 表示没碰上
                } else {
                    oDiv2.style.background = 'blue';
                }
                oDiv.style.left = ev.clientX - disX + 'px';
                oDiv.style.top = ev.clientY - disY + 'px';
            }
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            }
            return false;
        }
    }
</script>